package com.hibernate.hrm.entity.dto.contract;

import com.hibernate.hrm.entity.Contract;
import com.hibernate.hrm.entity.ContractFulfillment;
import com.hibernate.hrm.entity.User;
import lombok.Data;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

@Data
public class ContractDetailDTO {
    private Integer contractId;
    private String contractNumber;
    private String contractName;
    private Contract.ContractType contractType;
    private User signingPartyA;
    private User signingPartyB;
    private LocalDate effectiveDate;
    private LocalDate expiryDate;
    private Contract.ContractStatus status;
    private BigDecimal penaltyRate;
    private BigDecimal penaltyAmount;
    private Boolean isTransferable;
    private List<ContractFulfillment> fulfillments;
    private String legalClauseAnalysis;
    private Boolean isSignatureValid;
    private Boolean showSensitiveFields;
    private String workPosition;
    private String workLocation;
    private String entrustContent;
    private String entrustScope;
    private String serviceContent;


    public static ContractDetailDTO fromEntity(Contract contract, User currentUser) {
        ContractDetailDTO dto = new ContractDetailDTO();
        dto.setContractId(contract.getContractId());
        dto.setContractNumber(contract.getContractNumber());
        dto.setContractName(contract.getContractName());
        dto.setContractType(contract.getContractType());
        dto.setSigningPartyA(contract.getSigningPartyA());
        dto.setSigningPartyB(contract.getSigningPartyB());
        dto.setEffectiveDate(contract.getEffectiveDate());
        dto.setExpiryDate(contract.getExpiryDate());
        dto.setStatus(contract.getStatus());
        dto.setPenaltyRate(contract.getPenaltyRate());
        dto.setIsTransferable(contract.getIsTransferable());
        dto.setWorkPosition(contract.getWorkPosition());
        dto.setWorkLocation(contract.getWorkLocation());
        dto.setEntrustContent(contract.getEntrustContent());
        dto.setEntrustScope(contract.getEntrustScope());
        dto.setServiceContent(contract.getServiceContent());

        // 检查是否显示敏感字段
        boolean isHrOrLegal = "ROLE_HR_MGR".equals(currentUser.getRoleId().getRoleCode()) ||
                "ROLE_LEGAL".equals(currentUser.getRoleId().getRoleCode());
        dto.setShowSensitiveFields(isHrOrLegal);

        // 计算违约金金额（仅当显示敏感字段时）
        if (isHrOrLegal && contract.getStatus() == Contract.ContractStatus.逾期) {
            long overdueDays = LocalDate.now().until(contract.getExpiryDate()).getDays();
            dto.setPenaltyAmount(contract.getPenaltyRate().multiply(new BigDecimal(overdueDays)));
        }

        return dto;
    }
}
